<template>
  <div class="volunteer-home">
    <!-- 数据概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Timer /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.serviceHours || 0 }}</div>
              <div class="stats-label">服务时长（小时）</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><List /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.projectCount || 0 }}</div>
              <div class="stats-label">参与项目</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.teamCount || 0 }}</div>
              <div class="stats-label">加入队伍</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" v-loading="loading.stats">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.awardCount || 0 }}</div>
              <div class="stats-label">获得表彰</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card" v-loading="loading.hoursTrend">
          <template #header>
            <div class="card-header">
              <h3>服务时长趋势</h3>
              <el-select v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-option label="最近一周" value="week" />
                <el-option label="最近一月" value="month" />
                <el-option label="最近三月" value="quarter" />
              </el-select>
            </div>
          </template>
          <v-chart class="chart" :option="serviceChartOption" autoresize />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card" v-loading="loading.projectDistribution">
          <template #header>
            <div class="card-header">
              <h3>项目类型分布</h3>
            </div>
          </template>
          <v-chart class="chart" :option="projectChartOption" autoresize />
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-row :gutter="20" class="content-row">
      <el-col :span="16">
        <el-card class="recent-activities" v-loading="loading.recentActivities">
          <template #header>
            <div class="card-header">
              <h3>最近活动</h3>
              <el-button text type="primary" @click="goToActivities">查看全部</el-button>
            </div>
          </template>
          <div v-if="recentActivities.length === 0" class="empty-data">
            <el-empty description="暂无活动记录" />
          </div>
          <el-timeline v-else>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type">
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="upcoming-activities" v-loading="loading.upcomingActivities">
          <template #header>
            <div class="card-header">
              <h3>待参与活动</h3>
            </div>
          </template>
          <div v-if="upcomingActivities.length === 0" class="empty-data">
            <el-empty description="暂无待参与活动" />
          </div>
          <div v-else v-for="activity in upcomingActivities" 
               :key="activity.id" 
               class="upcoming-item">
            <div class="activity-info">
              <h4>{{ activity.name }}</h4>
              <p>{{ activity.time }}</p>
            </div>
            <el-button type="primary" link @click="viewActivityDetail(activity.id)">查看详情</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Timer, List, User, Trophy } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { 
  getVolunteerStats, 
  getServiceHoursTrend, 
  getProjectTypeDistribution, 
  getRecentActivities, 
  getUpcomingActivities 
} from '@/api/volunteer-dashboard'

use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const router = useRouter()
const timeRange = ref('month')

// 数据
const stats = ref({
  serviceHours: 0,
  projectCount: 0,
  teamCount: 0,
  awardCount: 0
})
const recentActivities = ref([])
const upcomingActivities = ref([])

// 加载状态
const loading = ref({
  stats: false,
  hoursTrend: false,
  projectDistribution: false,
  recentActivities: false,
  upcomingActivities: false
})

// 图表配置
const serviceChartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['服务时长']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    name: '小时'
  },
  series: [
    {
      name: '服务时长',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64,158,255,0.2)'
            },
            {
              offset: 1,
              color: 'rgba(64,158,255,0)'
            }
          ]
        }
      }
    }
  ]
})

const projectChartOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center'
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

// 获取志愿者数据概览
const fetchStats = async () => {
  loading.value.stats = true
  try {
    const res = await getVolunteerStats()
    stats.value = res.data
  } catch (error) {
    console.error('获取志愿者统计数据失败', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value.stats = false
  }
}

// 获取服务时长趋势
const fetchServiceHoursTrend = async () => {
  loading.value.hoursTrend = true
  try {
    const res = await getServiceHoursTrend({ timeRange: timeRange.value })
    serviceChartOption.value.xAxis.data = res.data.dates
    serviceChartOption.value.series[0].data = res.data.hours
  } catch (error) {
    console.error('获取服务时长趋势失败', error)
    ElMessage.error('获取服务时长趋势失败')
  } finally {
    loading.value.hoursTrend = false
  }
}

// 获取项目类型分布
const fetchProjectDistribution = async () => {
  loading.value.projectDistribution = true
  try {
    const res = await getProjectTypeDistribution()
    // 配置饼图颜色
    const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
    projectChartOption.value.series[0].data = res.data.map((item, index) => ({
      value: item.value,
      name: item.name,
      itemStyle: { color: colors[index % colors.length] }
    }))
  } catch (error) {
    console.error('获取项目类型分布失败', error)
    ElMessage.error('获取项目类型分布失败')
  } finally {
    loading.value.projectDistribution = false
  }
}

// 获取最近活动
const fetchRecentActivities = async () => {
  loading.value.recentActivities = true
  try {
    const res = await getRecentActivities()
    recentActivities.value = res.data
  } catch (error) {
    console.error('获取最近活动失败', error)
    ElMessage.error('获取最近活动失败')
  } finally {
    loading.value.recentActivities = false
  }
}

// 获取待参与活动
const fetchUpcomingActivities = async () => {
  loading.value.upcomingActivities = true
  try {
    const res = await getUpcomingActivities()
    upcomingActivities.value = res.data
  } catch (error) {
    console.error('获取待参与活动失败', error)
    ElMessage.error('获取待参与活动失败')
  } finally {
    loading.value.upcomingActivities = false
  }
}

// 查看活动详情
const viewActivityDetail = (id) => {
  router.push(`/volunteer/activities/${id}`)
}

// 跳转到活动列表
const goToActivities = () => {
  router.push('/volunteer/activities')
}

// 监听时间范围变化重新获取数据
const handleTimeRangeChange = () => {
  fetchServiceHoursTrend()
}

// 页面加载时获取所有数据
onMounted(() => {
  fetchStats()
  fetchServiceHoursTrend()
  fetchProjectDistribution()
  fetchRecentActivities()
  fetchUpcomingActivities()
})
</script>

<style scoped lang="scss">
.volunteer-home {
  .stats-row {
    margin-bottom: 20px;
  }

  .stats-card {
    .stats-content {
      display: flex;
      align-items: center;
      padding: 20px;

      .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background: #ecf5ff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          font-size: 24px;
          color: #409EFF;
        }
      }

      .stats-info {
        .stats-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          line-height: 1;
          margin-bottom: 8px;
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .content-row {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .upcoming-activities {
      .upcoming-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        .activity-info {
          h4 {
            margin: 0 0 4px;
            font-size: 14px;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 13px;
            color: #909399;
          }
        }
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;
    
    .chart-card {
      .chart {
        height: 300px;
      }
    }
  }
}
</style> 